<template>
  <div class="inline-flex items-center">
    <el-button
        type="primary"
        class="ml-4 flex items-center"
        @click="dialogVisible = true"
    >
      <i class="el-icon-magic-stick mr-1"></i>
      智能填写
    </el-button>

    <el-dialog
        v-model="dialogVisible"
        title="智能信息填写"
        width="500px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
      <div class="mb-4">
        <div class="flex items-center mb-2">
          <el-alert
              type="info"
              :closable="false"
              show-icon
          >
            <template #title>
              <span class="text-sm">支持粘贴参考文献格式文本，自动识别论文信息</span>
            </template>
          </el-alert>
        </div>

        <div class="mt-4">
          <p class="text-gray-600 text-sm mb-2">参考格式示例：</p>
          <p class="text-gray-500 text-xs bg-gray-50 p-2 rounded">
            作者名1,作者名2,论文标题[J].期刊名称,年(卷期):页码范围.
          </p>
        </div>

        <el-input
            type="textarea"
            v-model="citationText"
            :rows="4"
            placeholder="请在此粘贴参考文献格式文本"
            class="mt-4"
        ></el-input>
      </div>

      <template #footer>
        <div class="flex justify-end">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button
              type="primary"
              @click="handleSmartFill"
              :disabled="!citationText"
          >
            开始识别
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-ui'

const dialogVisible = ref(false)
const citationText = ref('')
const emit = defineEmits(['update:form'])

// 修改解析作者信息的函数
const parseAuthors = (text) => {
  // 匹配中文格式的作者名
  const authorPattern = /^([^,]+)(?:,|$)/g
  const authors = text.match(authorPattern) || []

  return authors.map((name, index) => ({
    rank: (index + 1).toString(),
    name: name.replace(',', '').trim(),
    identity: '老师', // 默认身份
    isCorresponding: index === 0, // 第一作者默认为通讯作者
    isCoFirstAuthor: false,
    institution: ''
  }))
}

// 修改解析年份的函数
const parseYear = (text) => {
  const yearPattern = /$$(\d{4})$$/
  const year = text.match(yearPattern)
  return year ? `${year[1]}-01-01` : ''
}

// 修改解析标题的函数
const parseTitle = (text) => {
  const titlePattern = /,([^,\[]+)\[/
  const titleMatch = text.match(titlePattern)
  return titleMatch ? titleMatch[1].trim() : ''
}

// 修改解析期刊信息的函数
const parseJournal = (text) => {
  const journalPattern = /\[J\]\.([^,]+)/
  const journal = text.match(journalPattern)
  return journal ? journal[1].trim() : ''
}

// 修改解析卷期号的函数
const parseVolumeAndIssue = (text) => {
  const pattern = /,\s*(\d+)$$(\d+)$$/
  const match = text.match(pattern)
  return {
    volume: match ? match[1] : '',
    issue: match ? match[2] : ''
  }
}

// 修改解析页码的函数
const parsePages = (text) => {
  const pagePattern = /:\s*(\d+)-(\d+)\./
  const pages = text.match(pagePattern)
  return pages ? `${pages[1]}~${pages[2]}` : ''
}

// 修改解析DOI的函数
const parseDOI = (text) => {
  const doiPattern = /https:\/\/doi\.org\/([^\s]+)/
  const doi = text.match(doiPattern)
  return doi ? doi[1] : ''
}

const handleSmartFill = () => {
  if (!citationText.value) {
    ElMessage.warning('请先粘贴参考文献文本')
    return
  }

  try {
    const text = citationText.value
    const volumeIssue = parseVolumeAndIssue(text)

    // 构建要更新的表单数据
    const formData = {
      title: parseTitle(text),
      authorInfo: parseAuthors(text),
      journalName: parseJournal(text),
      publishDate: parseYear(text),
      pageRange: parsePages(text),
      doi: parseDOI(text),
      volumeNumber: volumeIssue.volume,
      issueNumber: volumeIssue.issue,
      paperType: '期刊论文', // 默认类型
      researchField: '科研(自科)', // 默认领域
    }

    // 发出更新表单的事件
    emit('update:form', formData)

    ElMessage.success('智能填写完成')
    dialogVisible.value = false
    citationText.value = ''
  } catch (error) {
    console.error('解析错误:', error)
    ElMessage.error('解析失败，请检查输入格式是否正确')
  }
}
</script>

<style scoped>
:deep(.el-dialog__body) {
  padding-top: 10px;
}
</style>
